<template>
  <!-- 返工供应商索赔表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="50%"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120">
      <el-row>
        <el-col :span="11">
          <el-form-item label="索赔单号" prop="claimCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.claimCode"
              placeholder="请输入索赔单号"
              :disabled="true"
              clearable
            />

            <span v-else>{{ formData.claimCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="11" />
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item label="供应商" prop="supplierId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.supplierId"
              placeholder="请选择"
              clearable
              @change="changeSup"
              style="width: 400px"
              filterable
            >
              <el-option
                v-for="item in supList"
                :key="item.id"
                :label="item.partnerName"
                :value="item.id"
              />
            </el-select>

            <span v-else>{{ formData.supplierName }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="11">
          <el-form-item label="联系人" prop="contacts">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.contacts"
              placeholder="请输入联系人"
              clearable
            />

            <span v-else>{{ formData.contacts }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="联系人电话" prop="mobile">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.mobile"
              placeholder="请输入联系人电话"
              clearable
            />

            <span v-else>{{ formData.mobile }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="联系人邮箱" prop="email">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.email"
              placeholder="请输入联系人邮箱"
              clearable
            />

            <span v-else>{{ formData.email }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="11">
          <el-form-item label="" prop="isCustom">
            <el-checkbox
              v-if="!props.isReadonly"
              v-model="formData.isCustom"
              :true-label="1"
              :false-label="0"
            >
              是否客户索赔
            </el-checkbox>

            <span v-else>{{ formData.isCustom ? "是" : "否" }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="11">
          <el-form-item label="客户索赔单号" prop="customClaimCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.customClaimCode"
              placeholder="请输入客户索赔单号"
              clearable
            />

            <span v-else>{{ formData.customClaimCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="22">
          <el-form-item label="问题描述" prop="problemDesc">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.problemDesc"
              placeholder="请输入问题描述"
              clearable
            />

            <span v-else>{{ formData.problemDesc }}</span>
          </el-form-item>
        </el-col>
        <el-row>
          <el-col :span="17">
            <el-form-item label="异常通知单号" prop="rokNoticeId">
              <el-select
                v-if="!props.isReadonly"
                v-model="formData.rokNoticeId"
                placeholder="请选择"
                clearable
                @change="changeDoc"
                style="width: 400px"
                filterable
              >
                <el-option
                  v-for="item in docList"
                  :key="item.id"
                  :label="item.noticeCode"
                  :value="item.id"
                />
              </el-select>

              <span v-else>{{ formData.rokNoticeCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="11" />
        </el-row>

        <el-col :span="11">
          <el-form-item label="设备位置" prop="equipCode">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.equipCode"
              placeholder="请选择"
              clearable
              :disabled="true"
              style="width: 400px"
              filterable
            >
              <el-option
                v-for="item in docList"
                :key="item.id"
                :label="item.noticeCode"
                :value="item.id"
              />
            </el-select>

            <span v-else>{{ formData.equipCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="产品型号" prop="productCode">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.productCode"
              placeholder="请选择"
              clearable
              :disabled="true"
              style="width: 400px"
              filterable
            >
              <el-option
                v-for="item in docList"
                :key="item.id"
                :label="item.noticeCode"
                :value="item.id"
              />
            </el-select>

            <span v-else>{{ formData.productCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="产品名称" prop="productName">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.productName"
              placeholder="请选择"
              clearable
              :disabled="true"
              style="width: 400px"
              filterable
            >
              <el-option
                v-for="item in docList"
                :key="item.id"
                :label="item.noticeCode"
                :value="item.id"
              />
            </el-select>

            <span v-else>{{ formData.productName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="比例" prop="ratio">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.ratio"
              placeholder="请选择"
              clearable
              :disabled="true"
              style="width: 400px"
              filterable
            >
              <el-option
                v-for="item in docList"
                :key="item.id"
                :label="item.noticeCode"
                :value="item.id"
              />
            </el-select>

            <span v-else>{{ formData.ratio }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="索赔总额" prop="claimTotal">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.claimTotal"
              placeholder="请输入索赔总额"
              clearable
            />

            <span v-else>{{ formData.claimTotal }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="币种" prop="currency">
            <el-select
              style="width: 100%"
              v-if="!props.isReadonly"
              v-model="formData.currency"
              placeholder="请选择币种"
              clearable
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList('CurrencyType')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <span v-else>{{
              dictionaryStore.filterDictName("CurrencyType", formData.currency)
            }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="22">
          <el-form-item label="意见" prop="view">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.view"
              placeholder="请输入意见"
              type="textarea"
              clearable
            />

            <span v-else>{{ formData.view }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="附件上传">
        <CommonUploadFile
          :isRead="props.isReadonly"
          :files="formData.files"
          @update-files="updateFormFiles"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "QMSROKSUPPLIERCLAIMADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    console.log(props.isReadonly);
    visibleDialog.value = newVal;
    getdoc();
    getsup();
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
    generateNoticeCode();
  }
);
watch(
  () => props.isReadonly,
  (newVal: boolean) => {
    console.log(newVal);
  }
);
const rules = reactive({
  claimCode: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  supplierCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  supplierName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  contacts: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  mobile: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  email: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  customClaimCode: [
    { min: 1, max: 64, message: "长度在 1 到 64 个字符", trigger: "blur" },
  ],
  // isCustom: [
  //   { min: 1, max: 1, message: "长度在 1 到 1 个字符", trigger: "blur" },
  // ],
  problemDesc: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  view: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  claimTotal: [],
  currency: [],
  rokNoticeCode: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);
const loading1 = ref(false);
let formData = reactive({
  id: "",
  version: "",
  rokNoticeId: "",
  claimCode: "",
  supplierId: "",
  supplierCode: "",
  supplierName: "",
  contacts: "",
  mobile: "",
  email: "",
  customClaimCode: "",
  isCustom: "",
  problemDesc: "",
  view: "",
  claimTotal: "",
  currency: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  rokNoticeCode: "",
  productCode: "",
  productName: "",
  equipCode: "",
  equipName: "",
  ratio: "",
  files: [],
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        rokNoticeId,
        claimCode,
        supplierId,
        supplierCode,
        supplierName,
        contacts,
        mobile,
        email,
        customClaimCode,
        isCustom,
        problemDesc,
        view,
        claimTotal,
        currency,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        rokNoticeCode,
        productCode,
        productName,
        equipCode,
        equipName,
        ratio,
        files,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        rokNoticeId,
        claimCode,
        supplierId,
        supplierCode,
        supplierName,
        contacts,
        mobile,
        email,
        customClaimCode,
        isCustom,
        problemDesc,
        view,
        claimTotal,
        currency,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        rokNoticeCode,
        productCode,
        productName,
        equipCode,
        equipName,
        ratio,
        files: files ?? [],
      });
      console.log(formData.files);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  uploadKey.value = Math.random();
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.rokNoticeId = "";
  formData.claimCode = "";
  formData.supplierId = "";
  formData.supplierCode = "";
  formData.supplierName = "";
  formData.contacts = "";
  formData.mobile = "";
  formData.email = "";
  formData.customClaimCode = "";
  formData.isCustom = "";
  formData.problemDesc = "";
  formData.view = "";
  formData.claimTotal = "";
  formData.currency = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
  formData.rokNoticeCode = "";
  formData.productCode = "";
  formData.productName = "";
  formData.equipCode = "";
  formData.equipName = "";
  formData.ratio = "";
  formData.files = [];
}
const uploadKey = ref(Math.random());
const loading = ref(false);
function generateNoticeCode() {
  const randomNum = String(
    Math.floor(10000000 + Math.random() * 90000000)
  ).slice(-8);
  const claimCode = `PN${randomNum}`;
  formData.claimCode = claimCode;
}
// 图片处理
function updateFormFiles(val: []) {
  formData.files = val;
}
/** 返工供应商索赔保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/qms/roksupplierclaim/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}
const docList = ref([]);
const supList = ref([]);
const getdoc = async () => {
  const { data } = await request({
    url: "qms/roknoticedoc/getList",
    method: "post",
    data: {},
  });
  docList.value = data;
};
const getsup = async () => {
  const { data } = await request({
    url: "mdm/mdmpartner/getList",
    method: "get",
    data: {},
  });
  supList.value = data;
};
const changeDoc = (id: any) => {
  formData.rokNoticeId = id;
  formData.rokNoticeCode = docCode(id);
  formData.productCode = productCode(id);
  formData.productName = productName(id);
  formData.equipCode = equipCode(id);
  formData.equipName = equipName(id);
  formData.ratio = ratio(id);
  //工厂变更清除关联内容
  // formData.workshopId = "";
  // formData.workshopCode = "";
  // workCenters.value = [];
  // getWorkCenter();
};
const changeSup = (id: any) => {
  formData.supplierId = id;
  formData.supplierCode = supCode(id);
  formData.supplierName = supName(id);
};
const supCode = (id: string) => {
  if (id) {
    const data = supList.value.find((item) => item.id === id);
    return data.partnerCode;
  }
};
const supName = (id: string) => {
  if (id) {
    const data = supList.value.find((item) => item.id === id);
    return data.partnerName;
  }
};
const docCode = (id: string) => {
  if (id) {
    const data = docList.value.find((item) => item.id === id);
    return data.noticeCode;
  }
};
const productCode = (id: string) => {
  if (id) {
    const data = docList.value.find((item) => item.id === id);
    return data.productCode;
  }
};
const productName = (id: string) => {
  if (id) {
    const data = docList.value.find((item) => item.id === id);
    return data.productName;
  }
};
const equipCode = (id: string) => {
  if (id) {
    const data = docList.value.find((item) => item.id === id);
    return data.equipCode;
  }
};
const equipName = (id: string) => {
  if (id) {
    const data = docList.value.find((item) => item.id === id);
    return data.equipName;
  }
};
const ratio = (id: string) => {
  if (id) {
    const data = docList.value.find((item) => item.id === id);
    return data.ratio;
  }
};
async function getFiles() {
  let sondetails = await request({
    url: "/qms/roksupplierclaim/getFiles",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.files = sondetails.data;
  console.log(formData.files);
}
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
